import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { StepExecutionModel } from '#/api/production/models';

import { ref } from 'vue';

import dayjs from 'dayjs';

import { getFinishedMaterialListApi } from '#/api/master/material';
import { usPassResultOptions } from '#/api/production/models';

const rangePresets = ref([
  { label: '最近 7 天', value: [dayjs().add(-7, 'd'), dayjs()] },
  { label: '最近 14 天', value: [dayjs().add(-14, 'd'), dayjs()] },
  { label: '最近 30 天', value: [dayjs().add(-30, 'd'), dayjs()] },
  { label: '最近 90 天', value: [dayjs().add(-90, 'd'), dayjs()] },
]);

/** 获取表格查询表单的字段配置。 */
export function useSearchSchema(): VbenFormSchema[] {
  return [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        labelField: 'name',
        valueField: 'id',
        api: getFinishedMaterialListApi,
        immediate: false,
      },
      fieldName: 'productId',
      label: '产品',
    },
    {
      component: 'RangePicker',
      componentProps: {
        presets: rangePresets,
      },
      fieldName: 'rangeDate',
      label: '过站日期',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          { value: 'OK', label: '合格' },
          { value: 'NG', label: '不合格' },
        ],
      },
      fieldName: 'result',
      label: '过站状态',
    },
  ];
}

/**
 * 获取表格列配置。
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: OnActionClickFn<StepExecutionModel>,
): VxeTableGridOptions<StepExecutionModel>['columns'] {
  return [
    { type: 'seq', width: 60 },
    { field: 'sn', title: '零件码', minWidth: 160 },
    { field: 'productCode', title: '产品代码', width: 140 },
    { field: 'operationCode', title: '工序', width: 100 },
    { field: 'workstationCode', title: '工位', width: 100 },
    {
      field: 'passResult',
      title: '过站状态',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: usPassResultOptions(),
      },
    },
    { field: 'inboundTime', title: '进站时间', width: 150 },
    { field: 'outboundTime', title: '出站时间', width: 150 },
    { field: 'cycleTime', title: '用时(s)', width: 100 },
    {
      cellRender: {
        attrs: {
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'open',
            text: '过程数据',
          },
          {
            code: 'export',
            text: '导出',
          },
        ],
      },
      field: 'operation',
      fixed: 'right',
      title: '操作',
      width: 130,
    },
  ];
}
